import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../../../common/utils/format_util.dart';
import '../../../common/utils/level_util.dart';

import 'index.dart';

class UserInfoPage extends GetView<UserInfoController> {
  const UserInfoPage({super.key});
  
  /// 格式化活动发布时间
  String _formatPublishTime(String? timeStr) {
    if (timeStr == null || timeStr.isEmpty) return '';
    try {
      final dateTime = DateTime.parse(timeStr);
      return DateFormat('MM-dd HH:mm').format(dateTime);
    } catch (e) {
      return timeStr;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F5),
      body: Obx(() {
        if (controller.isLoading.value) {
          return const Center(
            child: CircularProgressIndicator(
              color: Color(0xFFD84545),
            ),
          );
        }

        final user = controller.userInfo.value;
        if (user == null) {
          return const Center(
            child: Text('用户信息加载失败'),
          );
        }

        return CustomScrollView(
          slivers: [
            // AppBar
            _buildAppBar(),
            
            // 用户信息卡片
            SliverToBoxAdapter(
              child: _buildUserInfoCard(user),
            ),
            
            // 白色信息卡片
            SliverToBoxAdapter(
              child: _buildInfoCard(user),
            ),
          ],
        );
      }),
    );
  }

  /// 构建AppBar
  Widget _buildAppBar() {
    return SliverAppBar(
      leading: IconButton(
        onPressed: () => Get.back(),
        icon: const Icon(Icons.arrow_back_ios_new_rounded),
      ),
      pinned: true,
      expandedHeight: 0,
      backgroundColor: const Color(0xFFD84545),
      foregroundColor: Colors.white,
      elevation: 0,
      title: const Text('用户主页'),
      centerTitle: true,
    );
  }

  /// 构建用户信息卡片
  Widget _buildUserInfoCard(dynamic user) {
    return Container(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [Color(0xFFD84545), Color(0xFFC73A3A)],
        ),
      ),
      padding: const EdgeInsets.all(16),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 左侧：用户相册
          Expanded(
            flex: 3,
            child: _buildUserAlbum(user),
          ),
          const SizedBox(width: 15),
          // 右侧：用户信息
          Expanded(
            flex: 2,
            child: _buildUserStats(user),
          ),
        ],
      ),
    );
  }

  /// 构建用户相册
  Widget _buildUserAlbum(dynamic user) {
    final userImages = user.userImgUrls as List<String>? ?? [];
    
    // 如果没有相册图片，显示默认占位
    if (userImages.isEmpty) {
      return AspectRatio(
        aspectRatio: 1,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(12),
          child: Container(
            color: Colors.grey[300],
            child: const Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.photo_library_outlined,
                    size: 48,
                    color: Colors.white,
                  ),
                  SizedBox(height: 8),
                  Text(
                    '暂无相册',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 12,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      );
    }
    
    // 显示相册轮播（一张一张显示）
    return _buildImageCarousel(userImages);
  }
  
  /// 构建图片轮播
  Widget _buildImageCarousel(List<String> images) {
    final PageController pageController = PageController();
    final currentPage = 0.obs;
    
    return AspectRatio(
      aspectRatio: 1,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: Stack(
          children: [
            // 图片轮播
            PageView.builder(
              controller: pageController,
              itemCount: images.length,
              onPageChanged: (index) {
                currentPage.value = index;
              },
              itemBuilder: (context, index) {
                return CachedNetworkImage(
                  imageUrl: images[index],
                  fit: BoxFit.cover,
                  placeholder: (context, url) => Container(
                    color: Colors.grey[300],
                    child: const Center(
                      child: CircularProgressIndicator(
                        color: Colors.white,
                      ),
                    ),
                  ),
                  errorWidget: (context, url, error) => Container(
                    color: Colors.grey[300],
                    child: const Icon(
                      Icons.broken_image,
                      size: 48,
                      color: Colors.white,
                    ),
                  ),
                );
              },
            ),
            
            // 指示器
            if (images.length > 1)
              Positioned(
                bottom: 8,
                left: 0,
                right: 0,
                child: Obx(() => Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: List.generate(
                    images.length,
                    (index) => Container(
                      width: 6,
                      height: 6,
                      margin: const EdgeInsets.symmetric(horizontal: 3),
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: currentPage.value == index
                            ? Colors.white
                            : Colors.white.withOpacity(0.4),
                      ),
                    ),
                  ),
                )),
              ),
          ],
        ),
      ),
    );
  }

  /// 构建用户统计信息
  Widget _buildUserStats(dynamic user) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        // 头像
        Container(
          width: 60,
          height: 60,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(30),
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(30),
            child: user.userAvatarUrl != null
                ? CachedNetworkImage(
                    imageUrl: user.userAvatarUrl!,
                    fit: BoxFit.cover,
                    placeholder: (context, url) => const Icon(Icons.person, size: 40),
                    errorWidget: (context, url, error) => const Icon(Icons.person, size: 40),
                  )
                : const Icon(Icons.person, size: 40),
          ),
        ),
        const SizedBox(height: 8),
        
        // 昵称
        Text(
          user.username ?? '用户',
          style: const TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        const SizedBox(height: 6),
        
        // 等级徽章
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
          decoration: BoxDecoration(
            color: Colors.white.withValues(alpha: 0.9),
            borderRadius: BorderRadius.circular(12),
          ),
          child: Text(
            LevelUtil.getLevelNameFromPoints(user.userPoints ?? 0),
            style: const TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              color: Color(0xFFD84545),
            ),
          ),
        ),
        const SizedBox(height: 12),
        
        // 统计数据
        Obx(() => Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _buildStatItem(
              FormatUtil.formatFollowers(controller.followerCount),
              controller.isMyself.value ? '好友数' : '粉丝数',
            ),
            Container(
              width: 1,
              height: 30,
              margin: const EdgeInsets.symmetric(horizontal: 8),
              color: Colors.white.withValues(alpha: 0.5),
            ),
            _buildStatItem(
              FormatUtil.formatLikes(user.userLikes ?? 0),
              '点赞数',
            ),
          ],
        )),
        const SizedBox(height: 10),
        
        // 加好友/聊天按钮
        Obx(() => _buildActionButton()),
      ],
    );
  }

  /// 构建统计项
  Widget _buildStatItem(String value, String label) {
    return Column(
      children: [
        Text(
          value,
          style: const TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
        const SizedBox(height: 2),
        Text(
          label,
          style: TextStyle(
            fontSize: 12,
            color: Colors.white.withValues(alpha: 0.9),
          ),
        ),
      ],
    );
  }

  /// 构建操作按钮
  Widget _buildActionButton() {
    // 如果是查看自己，不显示按钮
    if (controller.isMyself.value) {
      return const SizedBox.shrink();
    }

    // 如果是好友，显示聊天按钮
    if (controller.isFriend) {
      return _buildChatButton();
    }

    // 如果不是好友，检查是否显示加好友按钮
    if (controller.showAddFriendButton.value) {
      return _buildAddFriendButton();
    }

    return const SizedBox.shrink();
  }

  /// 构建加好友按钮
  Widget _buildAddFriendButton() {
    return SizedBox(
      width: double.infinity,
      height: 36,
      child: ElevatedButton(
        onPressed: controller.isAddingFriend.value
            ? null
            : controller.onAddFriend,
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.white.withValues(alpha: 0.95),
          foregroundColor: const Color(0xFFD84545),
          elevation: 0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(18),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 16),
        ),
        child: Text(
          controller.isAddingFriend.value ? '发送中...' : '加好友',
          style: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }

  /// 构建聊天按钮
  Widget _buildChatButton() {
    return SizedBox(
      width: double.infinity,
      height: 36,
      child: ElevatedButton.icon(
        onPressed: controller.onStartChat,
        style: ElevatedButton.styleFrom(
          backgroundColor: const Color(0xFF07C160),
          foregroundColor: Colors.white,
          elevation: 0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(18),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 16),
        ),
        icon: const Icon(Icons.chat, size: 16),
        label: const Text(
          '聊天',
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }

  /// 构建信息卡片
  Widget _buildInfoCard(dynamic user) {
    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 爱好标签
          _buildSection(
            title: '爱好:',
            child: _buildHobbyTags(user.userHobbies),
          ),
          const Divider(height: 24),
          
          // 个性签名
          _buildSection(
            title: '个性签名:',
            child: Text(
              user.userSignature ?? '这个人很懒，什么都没留下',
              style: const TextStyle(
                fontSize: 14,
                color: Color(0xFF666666),
                height: 1.6,
              ),
            ),
          ),
          const Divider(height: 24),
          
          // 常出没地
          _buildSection(
            title: '常出没地:',
            child: Text(
              user.userFrequentPlaces ?? '未知',
              style: const TextStyle(
                fontSize: 14,
                color: Color(0xFF666666),
              ),
            ),
          ),
          const Divider(height: 24),
          
          // 活动进行时
          _buildActivitySection(),
        ],
      ),
    );
  }

  /// 构建区块
  Widget _buildSection({
    required String title,
    required Widget child,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          title,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: Color(0xFF333333),
          ),
        ),
        const SizedBox(height: 10),
        child,
      ],
    );
  }

  /// 构建爱好标签（单行滚动显示）
  Widget _buildHobbyTags(List<String>? hobbies) {
    final allHobbies = ['吃', '喝', '玩', '乐', '购'];
    final selectedHobbies = hobbies ?? [];

    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Row(
        children: allHobbies.map((hobby) {
          final isSelected = selectedHobbies.contains(hobby);
          return Container(
            margin: const EdgeInsets.only(right: 12),
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 6),
            decoration: BoxDecoration(
              color: isSelected ? const Color(0xFFD84545) : const Color(0xFFF0F0F0),
              borderRadius: BorderRadius.circular(20),
              boxShadow: isSelected
                  ? [
                      BoxShadow(
                        color: const Color(0xFFD84545).withOpacity(0.3),
                        blurRadius: 8,
                        offset: const Offset(0, 2),
                      ),
                    ]
                  : null,
            ),
            child: Text(
              hobby,
              style: TextStyle(
                fontSize: 14,
                color: isSelected ? Colors.white : const Color(0xFF666666),
                fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  /// 构建活动区块
  Widget _buildActivitySection() {
    return Obx(() {
      final activities = controller.activities;
      
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题行
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '活动进行时',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: Color(0xFF333333),
                ),
              ),
              if (controller.isMyself.value)
                GestureDetector(
                  onTap: controller.goToHistory,
                  child: Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 6,
                    ),
                    decoration: BoxDecoration(
                      color: const Color(0xFFF5F5F5),
                      borderRadius: BorderRadius.circular(16),
                    ),
                    child: const Text(
                      '历史记录',
                      style: TextStyle(
                        fontSize: 14,
                        color: Color(0xFF666666),
                      ),
                    ),
                  ),
                ),
            ],
          ),
          const SizedBox(height: 10),
          
          // 活动列表
          if (activities.isEmpty)
            const Padding(
              padding: EdgeInsets.symmetric(vertical: 16),
              child: Center(
                child: Text(
                  '暂无进行中的活动',
                  style: TextStyle(
                    fontSize: 14,
                    color: Color(0xFF999999),
                  ),
                ),
              ),
            )
          else
            ...activities.asMap().entries.map((entry) {
              final index = entry.key;
              final activity = entry.value;
              return _buildActivityItem(activity, index);
            }),
        ],
      );
    });
  }

  /// 构建活动项
  Widget _buildActivityItem(dynamic activity, int index) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: const Color(0xFFFAFAFA),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: const Color(0xFFF0F0F0),
        ),
      ),
      child: Row(
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _formatPublishTime(activity.activityPublishTime),
                  style: const TextStyle(
                    fontSize: 12,
                    color: Color(0xFF999999),
                  ),
                ),
                const SizedBox(height: 6),
                Text(
                  activity.activityTitle ?? '无标题',
                  style: const TextStyle(
                    fontSize: 14,
                    color: Color(0xFF333333),
                    fontWeight: FontWeight.w500,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          ),
          if (!controller.isMyself.value) ...[
            const SizedBox(width: 12),
            ElevatedButton(
              onPressed: () => controller.onJoinActivity(index),
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFFD84545),
                foregroundColor: Colors.white,
                elevation: 0,
                padding: const EdgeInsets.symmetric(
                  horizontal: 20,
                  vertical: 10,
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20),
                ),
              ),
              child: const Text(
                '申请加入',
                style: TextStyle(fontSize: 12),
              ),
            ),
          ],
        ],
      ),
    );
  }
}
